package stu.day9_day18;


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class LeetCode142 {
    public ListNode detectCycle(ListNode head) {

        ListNode fast = head;
        ListNode slow = head;

        if(head==null){
            return null;
        }

        slow = slow.next;
        fast = fast.next==null?null:fast.next.next;

        while (true){
            if(fast==null ){
                return null;
            }
            if(fast.next==null){
                return null;
            }

            if(fast != slow){
                slow = slow.next;
                fast = fast.next.next;
            }else if(fast == slow){
                break;
            }
        }

        ListNode neh = head;

        while (neh!=slow){
            neh = neh.next;
            slow = slow.next;
        }

        return slow;


    }
}